﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Xml.Linq;

namespace MShop.Core.Util
{
    public class UrlUtil
    {
        private UrlUtil() { }
        public static string GetApplicationPath()
        {
            return Text.EnsureTrailingSlash(HttpContext.Current.Request.ApplicationPath);
        }


        public static string GetRealIp()
        {
            string UserIP;
            if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null) //得到穿过代理服务器的ip地址
            {
                UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            }
            else
            {
                UserIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
            }
            return UserIP;
        }


        /// <summary>
        /// Get the (lowercase) url of the site without any trailing slashes.
        /// </summary>
        /// <returns></returns>
        public static string GetSiteUrl()
        {
            string path = HttpContext.Current.Request.ApplicationPath;
            if (path.EndsWith("/") && path.Length == 1)
            {
                return GetHostUrl();
            }
            else
            {
                return GetHostUrl() + path.ToLower();
            }
        }

        public static string GetSeearchUrl(string key,int id)
        {
            if (!string.IsNullOrEmpty(key))
            {
                System.Xml.Linq.XDocument doc = XDocument.Load(HttpContext.Current.Server.MapPath("/config/searchurl.config"));
                IEnumerable<XElement> elements= doc.Root.Elements("url");
                var q = from item in elements where item.Attribute("key").Value==key select item;
                if (q.FirstOrDefault() != null)
                {
                    return string.Format(q.FirstOrDefault().Attribute("value").Value, id);
                }
                else
                {
                    throw new ArgumentNullException("XElement is null");
                }
            }
            return null;
        }


        public static string GetSeearchUrl(Type entity, int id)
        {
            if (entity == null)
                return null;
            return GetSeearchUrl(entity.Name.ToLower(), id);
        }        

        /// <summary>
        /// Returns a formatted url for a rss feed for a given section 
        /// (http://{hostname}/{ApplicationPath}/{Section.Id}/rss.aspx).
        /// </summary>
        /// <param name="section"></param>
        /// <returns></returns>
        public static string GetRssUrlFromSite()
        {
            return GetHostUrl() + GetApplicationPath() +  "/feed.aspx";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pathInfo"></param>
        /// <returns></returns>
        public static string[] GetParamsFromPathInfo(string pathInfo)
        {
            if (pathInfo.Length > 0)
            {
                if (pathInfo.EndsWith("/"))
                {
                    pathInfo = pathInfo.Substring(0, pathInfo.Length - 1);
                }
                pathInfo = pathInfo.Substring(1, pathInfo.Length - 1);
                return pathInfo.Split(new char[] { '/' });
            }
            else
            {
                return null;
            }
        }

        public static string GetHostUrl()
        {
            string securePort = HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"];
            string protocol = securePort == null || securePort == "0" ? "http" : "https";
            string serverPort = HttpContext.Current.Request.ServerVariables["SERVER_PORT"];
            string port = serverPort == "80" ? string.Empty : ":" + serverPort;
            string serverName = HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
            return string.Format("{0}://{1}{2}", protocol, serverName, port);
        }
    }
}
